﻿// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;

using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using svs.Mobile.BeyondMedia.FeedCore.Helpers;
using svs.Mobile.BeyondMedia.FeedCore.RSS.Entities;

namespace svs.Mobile.BeyondMedia.FeedCore.RSS.Aggregators
{
		public class CategoryAggregate
		{
			const string AggregatorURL = "http://feedaggregator.beyondpod.mobi";

			public CategoryAggregate(FeedCategory category)
			{
				Category = category;
			}

			public CategoryAggregate(Uri uri)
			{
				if(!IsAggreagateFeed(uri))
					throw new ApplicationException(string.Format("The uri {0} is not an aggreagate feed uri!", uri));

				Regex regex = new Regex(
					@".*c=(?<Category>.*)",
					RegexOptions.IgnoreCase
					| RegexOptions.Multiline
					| RegexOptions.IgnorePatternWhitespace
					| RegexOptions.Compiled
					);

				string parameters = HttpUtility.UrlDecode(uri.Query);

				Match m = regex.Match(parameters);

				if (m.Groups["Category"].Success)
				{
					Category = CategoryManager.GetCategoryByValue(m.Groups["Category"].Value);
				}

				if (Category == null || Category.Equals(CategoryManager.CategoryNull))
					Category = CategoryManager.AllFeeds;
			}

			public FeedCategory Category
			{ 
				get;
				set;
			}

			public Uri ToUrl()
			{
				return new Uri(string.Format("{0}?c={1}",AggregatorURL, HttpUtility.UrlEncode(Category.Value)));
			}

			public static bool IsAggreagateFeed(Uri uri)
			{
				return uri.AbsoluteUri.StartsWith(AggregatorURL, StringComparison.InvariantCultureIgnoreCase);
			}

			public List<RssFeedItem> GetAggregateRssItems()
			{
				var aggregate = new List<RssFeedItem>();

				foreach (var categoryFeed in FeedRepository.GetFeedsInCategory(Category))
				{
					if(!categoryFeed.HasUrl)
						continue;

					RssFeed rss;
					try
					{
						rss = RssFeedCache.LoadFromCache(categoryFeed);
					}
					catch
					{
						continue;					
					}
					 
					if (rss == null)
						continue;

					var selectedFeedItems = new List<RssFeedItem>();
					foreach (var item in rss.Items)
					{
						if (!item.Read)
						{
							if (selectedFeedItems.Count < categoryFeed.NumToIncludeInWhatIsNew)
								selectedFeedItems.Add(item);
							else
								break;
						}
					}

					aggregate.AddRange(selectedFeedItems);
				}

				return aggregate;
			}

		}
}
